import React from 'react';
import { connect } from 'react-redux';
import echarts from 'echarts';
import FilterTool from '../../../components/FilterTool';
import CommonListsIndex from '../../../components/CommonLists/index';
import SpreadBar from '../../Dashboard/component/spreadBar';
import RequestTrend from '../../Dashboard/component/requestTrend';
import { Button, Row, Col, Icon, Radio, message, Card, DatePicker, Upload, Tooltip, Alert } from 'antd';
import services from '../../../services/api';
import { headerModules } from '../../../utils/utils';
import './index.less';
import moment from 'moment';
import { APIUrl } from '../../../services/createServices';
import HitList from './list';
import ErrorList from './error';
import StrategiesList from '../../Case/Check/Detail/list';
import Modal from '../../../components/Modal/index';
import storage from '../../../utils/storage';
// import EventDetail from '../../Monitor/Event/detail'
import { LABS_SOURCE_TYPE, LABS_STATUS } from '../../../utils/constant';

const { RangePicker } = DatePicker;

function mapStateToProps(state) {
  return {
    strategy_type: state.code.strategy_type || [],
    strategy_mode: state.code.strategy_mode || [],
    risk_level: state.code.risk_level || [],
    menu: state.menu,
  };
}

@connect(mapStateToProps)
class LabDetail extends CommonListsIndex {
  constructor(props) {
    super(props);
    this.queryParams = {};
    this.queryPanigation = {
      current_page: 1,
      page_size: 10,
    };
    this.queryTableParams = {};
    this.editComponent = `/strategyLabs/${props.match.params.id}/detail/id/details`;
    this.state = {
      source_type: 3,
      lab_id: props.match.params.id,
      strategy_list: [],
      requests: [],
      fileList: [],
      hit_detail: [],
      historyStart: moment()
        .subtract(1, 'days')
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss'),
      historyEnd: moment()
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss'),
      list: [],
      totalCount: 0,
      progress: -1,
      variables: {},
      detailLoad: false,
      errorLists: [],
      running: false,
      applications: [],
      events: [],
      products: [],
      selectedRowKeys: [],
      selectedRows: [],
      isSelectedAll: false,
    };
    this.api = 'strategyLabsApi';
    this.step = 1;
    this.timeOut = null;
    this.timeOutHit = null;
    this.timeOutDetail = null;
    this.time = 5000;
    this.queryErrorPanigation = Object.assign({}, this.initQueryPanigation); //分页参数
    this.requestParam = { ...this.queryParams, lab_id: this.state.lab_id };
  }

  componentDidMount() {
    this.getDetailList();
  }

  componentWillUnmount() {
    clearTimeout(this.timeOut);
    clearTimeout(this.timeOutHit);
    clearTimeout(this.timeOutDetail);
    this.timeOut = null;
    this.timeOutHit = null;
    this.timeOutDetail = null;
  }

  getDetailList = () => {
    return services[this.api].detailList({ lab_id: this.state.lab_id }).then((res) => {
      if (res.code === 0) {
        const { source_start_time, source_end_time, ...otherData } = res.data;

        // 如果数据来自历史数据或者自定义数据，且正在进行中，则去轮询进度
        if (
          (res.data.source_type === LABS_SOURCE_TYPE._HISTORY || res.data.source_type === LABS_SOURCE_TYPE._COMSTOM) &&
          res.data.status === LABS_STATUS._RUNNING
        ) {
          this.setState(
            {
              ...otherData,
              detailLoad: true,
              running: true,
              source_type: res.data.source_type === 0 ? LABS_SOURCE_TYPE._ONLINE : res.data.source_type,
            },
            () => {
              this.getProgress();
            }
          );
        } else {
          console.log('停止了呀');
          this.setState({
            source_start_time,
            source_end_time,
            historyStart: source_start_time
              ? moment(source_start_time).format('YYYY-MM-DD HH:mm:ss')
              : moment()
                  .subtract(7, 'd')
                  .startOf('day')
                  .format('YYYY-MM-DD HH:mm:ss'),
            historyEnd: source_end_time
              ? moment(source_end_time).format('YYYY-MM-DD HH:mm:ss')
              : moment().format('YYYY-MM-DD HH:mm:ss'),
            ...otherData,
            detailLoad: true,
            running: false,
            source_type: res.data.source_type === 0 ? LABS_SOURCE_TYPE._ONLINE : res.data.source_type,
          });
        }
      } else {
        message.error(res.msg);
      }
    });
  };

  getTacticsLabsDetail = (params) => {
    clearTimeout(this.timeOutDetail);
    services[this.api]
      .getTacticsLabsDetail({
        lab_id: this.state.lab_id,
        source: this.state.source_type,
        ...params,
      })
      .then((res) => {
        if (res.code === 0) {
          this.setState(
            {
              ...res.data,
            },
            () => {
              // this.drawStrategyTrend();
              // this.drawStrategyProportion();
            }
          );
          if (this.state.source_type === LABS_SOURCE_TYPE._ONLINE && this.state.status === LABS_STATUS._RUNNING) {
            this.timeOutDetail = setTimeout(() => {
              this.getTacticsLabsDetail(params);
            }, this.time);
          }
        } else {
          console.error(res.msg);
        }
      });
  };

  getHitList = (params) => {
    clearTimeout(this.timeOutHit);
    services[this.api]
      .getHitList({
        lab_id: this.state.lab_id,
        ...params,
      })
      .then((res) => {
        if (res.code === 0) {
          const { list, totalCount } = res.data
          const currentPage = params.current_page
          const page = Math.ceil(totalCount / this.queryPanigation.page_size)
          if (list && totalCount && list.length === 0 && currentPage > page) {
            this.onChangePagination(page, 'current_page')
          } else {
            this.setState({
              ...res.data,
            });
          }
          // this.setState({
          //   ...res.data,
          // });
          if (this.state.source_type === LABS_SOURCE_TYPE._ONLINE && this.state.status === LABS_STATUS._RUNNING) {
            this.timeOutHit = setTimeout(() => {
              if (moment().isBefore(this.state.source_start_time)) {
                message.warn('本地时间与实验开始时间冲突，请同步本地时间')
              }
              const end_times = moment().isBefore(this.state.source_start_time) ? moment(this.state.source_start_time).format('YYYY-MM-DD HH:mm:ss') : moment().format('YYYY-MM-DD HH:mm:ss');
              this.setState(
                {
                  source_end_time: end_times,
                },
                () => {
                  params.end = end_times;
                  this.getHitList(params);
                }
              );
            }, this.time);
          }
        } else {
          message.error(res.msg);
        }
      });
  };

  getErrorList = (params) => {
    services[this.api]
      .getErrorList({
        lab_id: this.state.lab_id,
        ...params,
      })
      .then((res) => {
        if (res.code === 0) {
          const { list, totalCount } = res.data
          const currentPage = params.current_page
          const page = Math.ceil(totalCount / this.queryPanigation.page_size)
          if (list && totalCount && list.length === 0 && currentPage > page) {
            this.onChangePaginationError(page, 'current_page')
          } else {
            this.setState({
              errorLists: { ...res.data }
            });
          }
          // this.setState({
          //   errorLists: { ...res.data },
          // });
        } else {
          message.error(res.msg);
        }
      });
  };

  resultDownAll = () => {
    Modal.open({
      title: '',
      width: '360px',
      isConfirm: true,
      content: <p>仅支持10000条以内的数据下载，是否确认下载？</p>,
      isOkBtn: true,
      isCancelBtn: true,
      ok: () => {
        this.resultDownload(true)
        Modal.close();
      },
      cancel: () => {
        Modal.close();
      },
    });
  }

  // 实验结果下载
  resultDownload = (export_all) => {
    const { selectedRowKeys } = this.state;
    if (!export_all) {
      // 非下载全部
      if (selectedRowKeys.length === 0) return message.warn('请选择数据');
      if (selectedRowKeys.length > 10000) return message.warn('仅支持10000条以内的数据下载，请重新勾选！');
    }
    let json = JSON.stringify({
      lab_id: this.state.lab_id,
      req_id: export_all ? [] : this.state.selectedRowKeys,
      export_all,
    });
    let params = {
      p: window.btoa(json),
    };
    let url = this.getParamsUrl(`${APIUrl}/strategy-lab/experiment-hit-download`, params);
    let a = document.createElement('a'); // 创建a标签
    a.href = url; // 设置下载地址
    a.download = ''; // 设置下载文件名
    a.click();
    a.remove();
  };

  // 处理get 参数
  getParamsUrl = (url, params) => {
    if (Object.keys(params).length !== 0) {
      let str = '';
      for (const key in params) {
        str = str !== '' ? `${str}&${key}=${params[key]}` : `${key}=${params[key]}`;
      }
      return `${url}?${str}`;
    } else {
      return url;
    }
  };

  onSourceChange = (e) => {
    this.setState({
      source_type: e.target.value,
    });
  };

  refreshFilter = (params, isSummit) => {
    if (isSummit !== undefined) {
      return;
    }
    if (params) {
      this.queryParams = params;
      this.requestParam = { ...this.queryParams, lab_id: this.state.lab_id };
    }
    this.updatePanagaition(this.initQueryPanigation);
    this.updateErrorPanagaition(this.initQueryPanigation);
    this.getTacticsLabsDetail(this.queryParams);
    this.freshHitList();
    this.freshErrorQueryList();
  };
  freshQueryList = () => {
    this.freshHitList();
  };

  freshHitList = () => {
    this.queryList({ ...this.queryPanigation, ...this.queryTableParams, ...this.queryParams });
  };

  // 筛选列表，含参数
  freshErrorQueryList = () => {
    this.getErrorList({ ...this.queryParams, ...this.queryTableParams, ...this.queryErrorPanigation });
  };
  // 打开新窗口、页面的id
  getOpenParam = (record) => {
    return record.req_id;
  };
  queryList(params) {
    this.getHitList(params);
  }

  // 下载示例文件
  downloadExample = () => {
    var xhr = new XMLHttpRequest(); //定义http请求对象
    xhr.open('get', APIUrl + '/strategy-lab/source-template-download?lab_id=' + this.state.lab_id, true);
    xhr.setRequestHeader('token', storage.token);
    xhr.setRequestHeader('X-User-Dept-Id', storage.dept);
    xhr.send();
    xhr.responseType = 'blob'; // 返回类型blob
    xhr.onload = (e) => {
      // 定义请求完成的处理函数，请求前也可以增加加载框/禁用下载按钮逻辑
      if (xhr.status === 200 && xhr.readyState === 4) {
        var blob = xhr.response;
        var reader = new FileReader();
        reader.onloadend = (e) => {
          // 转换完成，创建一个a标签用于下载
          var a = document.createElement('a');
          a.download = `示例文件_${this.state.app_id}_${this.state.event_id}_${moment().format('YYYYMMDDHHmmss')}.xlsx`; //自定义下载文件名称
          a.href = e.target.result;
          a.click();
        };
        reader.readAsDataURL(blob); // 转换为base64，可以直接放入a标签href
      }
    };
  };

  // drawStrategyTrend = () => {
  //   const option = {
  //     tooltip: {
  //       trigger: 'axis',
  //     },
  //     legend: {
  //       data: this.state.strategy_trend.map((item) => {
  //         return item.name;
  //       }),
  //     },
  //     grid: {
  //       left: '3%',
  //       right: '4%',
  //       bottom: '3%',
  //       containLabel: true,
  //     },
  //     xAxis: {
  //       type: 'category',
  //       boundaryGap: false,
  //       data: this.state.strategy_trend[0].value.map((item) => {
  //         return item.index;
  //       }),
  //     },
  //     yAxis: {
  //       type: 'value',
  //     },
  //     series: this.state.strategy_trend.map((item) => {
  //       return {
  //         name: item.name,
  //         type: 'line',
  //         stack: item.name,
  //         data: item.value.map((item) => {
  //           return item.requests;
  //         }),
  //       };
  //     }),
  //   };
  //   echarts.init(this.refs.strategyTrend).setOption(option);
  // };

  drawStrategyProportion = () => {
    const option = {
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        data: this.state.strategy_hit_rate.map((item) => {
          return item.name;
        }),
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: {
        type: 'value',
      },
      yAxis: {
        type: 'category',
        data: this.state.strategy_hit_rate.map((item) => {
          return item.index;
        }),
      },
      series: [
        {
          name: '策略命中',
          type: 'bar',
          stack: 'bar',
          barMaxWidth: 50,
          data: this.state.strategy_hit_rate.map((item) => {
            return item.requests;
          }),
        },
      ],
    };
    echarts.init(this.refs.strategyProportion).setOption(option);
  };

  onUploadChange = (res) => {
    this.setState({
      fileList: [...res.fileList],
    });

    if (res.file.status === 'done') {
      if (res.file.response.code === 0) {
        this.setState({
          fileList: [res.file],
        });
      } else {
        this.setState({
          fileList: [],
        });
        message.error(res.file.response.msg);
      }
    } else if (res.file.status === 'removed') {
      this.setState({
        fileList: [],
      });
    } else if (res.file.status === 'error') {
      message.error(res.file.response.message);
      this.setState({
        fileList: [],
      });
    }
  };

  clearFile() {
    this.setState({
      fileList: [],
    });
  }

  startTest = () => {
    const params = {
      lab_id: this.state.lab_id,
      source_type: this.state.source_type,
    };

    switch (this.state.source_type) {
      case 1:
        break;
      case 2:
        params.source_start_time = this.state.historyStart;
        params.source_end_time = this.state.historyEnd;
        params.step = this.step;
        break;
      case 3:
        if (this.state.fileList && this.state.fileList.length > 0) {
        } else {
          message.error('请先上传正确的数据文件，再进行试验！');
          return;
        }
        break;
      default:
        break;
    }
    this.clearSelected();
    services[this.api].startTest(params).then((res) => {
      if (res.code === 0) {
        if (this.state.source_type === 2) {
          if (this.step === 1) {
            this.showHistoryTips(res.data);
          } else {
            const start_times = JSON.parse(JSON.stringify(this.state.historyStart));
            const end_times = JSON.parse(JSON.stringify(this.state.historyEnd));
            this.setState({
              source_start_time: '',
              source_end_time: '',
            });
            this.setState(
              {
                source_start_time: start_times,
                source_end_time: end_times,
                running: true,
              },
              () => {
                // console.log('暑假', this.props.from, this.state.source_start_time, this.state.source_end_time)
                this.getProgress();
              }
            );

            this.getDetailList();
            Modal.close();
          }
        } else if (this.state.source_type === 1) {
          this.getDetailList();
          // .then(() => {
          //   this.getTacticsLabsDetail();
          // });
          message.success('当有数据接入时可在报表中看到试算结果');
        } else if (this.state.source_type === 3) {
          this.setState(
            {
              fileList: [],
              running: true,
            },
            () => {
              this.getProgress();
            }
          );
          this.getDetailList().then(() => {
            this.getTacticsLabsDetail(this.queryParams);
          });
          message.success('试验计算中');
        } else {
          this.getDetailList();
        }
      } else {
        message.error(res.msg);
      }
    });
  };

  getProgress = () => {
    clearTimeout(this.timeOut);
    if (!this.state.running) {
      return;
    }
    services[this.api].getProgress({ lab_id: this.state.lab_id }).then((res) => {
      if (res.code === 0) {
        this.setState({
          progress: res.data.processing,
        });
        if (res.data.processing < 100) {
          this.timeOut = setTimeout(this.getProgress, 2000);
        } else {
          this.getDetailList();
          this.refreshFilter();
        }
      } else {
        message.error(res.msg);
      }
    });
  };
  detail = (rescord) => {};
  showHistoryTips = (data) => {
    Modal.open({
      title: '确认开始试算？',
      width: '300px',
      content: (
        <p>
          您选择的ES数据共<span style={{ color: '#f78120' }}>{data.total}</span>条记录，预计试算时间
          <span style={{ color: '#f78120' }}>{data.minute}</span>分钟，是否开始试算？
        </p>
      ),
      isOkBtn: true,
      isCancelBtn: true,
      ok: () => {
        this.step = 2;
        this.startTest();
      },
      cancel: () => {
        this.step = 1;
        Modal.close();
      },
    });
  };

  endTest = () => {
    const params = {
      lab_id: this.state.lab_id,
    };
    services[this.api].endTest(params).then((res) => {
      if (res.code === 0) {
        clearTimeout(this.timeOut);
        this.setState(
          {
            progress: -1,
            running: false,
          },
          () => {
            this.getDetailList();
            this.step = 1;
          }
        );
      } else {
        message.error(res.msg);
      }
    });
  };

  expandedRowRender = (record) => {
    return (
      <StrategiesList
        edit={this.edit}
        list={record.strategies}
        showDetail={this.showDetail}
        editFunction='showField'
        variables={record.variables}
        rowKey={'strategy_id'}
      />
    );
  };
  // 命中详情
  HitDetail = (params) => {
    const param = {
      actionType: 'strategyLabsApi',
      params: {
        lab_id: this.state.lab_id,
      },
    };
    storage.HitDetail = param;
    this.showDetail(params);
  };

  // 仅更新筛选分页的参数
  updateErrorPanagaition = (params) => {
    this.queryErrorPanigation = {
      ...this.queryErrorPanigation,
      ...params,
    };
  };

  // 分页回调
  onChangePaginationError = (pageNumber, type = 'current_page') => {
    if (this.state.previousId && this.state.nextId && this.state.previousPage && this.state.totalCount) {
      this.updateErrorPanagaition &&
        this.updateErrorPanagaition({
          [type]: pageNumber,
          previous_id: this.state.previousId,
          next_id: this.state.nextId,
          previous_page: this.state.previousPage,
          total_count: this.state.totalCount,
        });
    } else {
      this.updateErrorPanagaition &&
        this.updateErrorPanagaition({
          [type]: pageNumber,
        });
    }
    this.freshErrorQueryList();
  };

  // 分页回调
  onChangePagination = (pageNumber, type = 'current_page') => {
    if (this.state.previousId && this.state.nextId && this.state.previousPage && this.state.totalCount) {
      this.updatePanagaition &&
        this.updatePanagaition({
          [type]: pageNumber,
          previous_id: this.state.previousId,
          next_id: this.state.nextId,
          previous_page: this.state.previousPage,
          total_count: this.state.totalCount,
        });
    } else {
      this.updatePanagaition &&
        this.updatePanagaition({
          [type]: pageNumber,
        });
    }
    this.freshHitList();
  };
  openShowError = (text) => {
    Modal.open({
      title: '异常详情',
      content: <div style={{ padding: '20px' }}>{text}</div>,
      width: '80%',
      isOkBtn: true,
      maskClosable: false,
      isCancelBtn: true,
      ok: () => Modal.close(),
    });
  };

  clearSelected = () => {
    this.setState({
      selectedRowKeys: [],
      selectedRows: [],
    });
  };

  render() {
    const { selectedRowKeys, isSelectedAll} = this.state;
    const isKnownTime = this.state.source_start_time !== '' && this.state.source_end_time !== '';
    const filterItems = [
      {
        type: 'rangepicker',
        key: 'start',
        name: ['start', 'end'],
        label: '',
        defaultValue: [
          this.state.source_start_time
            ? moment(this.state.source_start_time).format('YYYY-MM-DD HH:mm:ss')
            : moment().format('YYYY-MM-DD HH:mm:ss'),
          this.state.source_end_time
            ? moment(this.state.source_end_time).format('YYYY-MM-DD HH:mm:ss')
            : this.state.source_start_time
            ? moment().isBefore(this.state.source_start_time)
              ? moment(this.state.source_start_time).format('YYYY-MM-DD HH:mm:ss')
              : moment().format('YYYY-MM-DD HH:mm:ss')
            : moment().format('YYYY-MM-DD HH:mm:ss'),
        ],
        format: 'YYYY-MM-DD HH:mm:ss',
        placeholder: ['起始时间', '结束时间'],
        disabledDate: (current) => {
          return current && current > moment().endOf('day');
        },
      },
    ];
    const columns = [
      {
        title: '请求ID',
        key: 'req_id',
        dataIndex: 'req_id',
        ellipsis: true,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
      {
        title: '请求时间',
        key: 'req_time',
        dataIndex: 'req_time',
        ellipsis: true,
        render: (text, record) => {
          const time = moment(text).format('YYYY-MM-DD HH:mm:ss');
          return (
            <Tooltip title={time} placement='topLeft'>
              {time}
            </Tooltip>
          );
        },
      },
      {
        title: '请求策略',
        key: 'hit_strategy_name',
        dataIndex: 'hit_strategy_name',
        ellipsis: true,
        render: (text, record) => {
          const value = record.risk_level === 'pass' && text === '' ? '无' : text;
          return (
            <Tooltip title={value} placement='topLeft'>
              {value}
            </Tooltip>
          );
        },
      },
      {
        title: (
          <>
            {this.getFilterTitle('评估结果', this.props.risk_level, 'risk_level', this.refreshTableFilter, [
              'key',
              'value',
            ])}
          </>
        ),
        key: 'risk_level',
        dataIndex: 'risk_level',
        ellipsis: true,
        render: (text, record) => {
          const value =
            this.props.risk_level.filter((item) => item.key === record.risk_level)[0] &&
            this.props.risk_level.filter((item) => item.key === record.risk_level)[0].value;
          return (
            <Tooltip title={value} placement='topLeft'>
              {value}
            </Tooltip>
          );
        },
      },
      {
        title: '所属渠道',
        dataIndex: 'app_name',
        key: 'app_name',
        ellipsis: true,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
      {
        title: '所属产品',
        dataIndex: 'product_name',
        key: 'product_name',
        ellipsis: true,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
      {
        title: '关联事件',
        dataIndex: 'event_name',
        key: 'event_name',
        ellipsis: true,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
      {
        title: '用户ID',
        key: 'user_id',
        dataIndex: 'user_id',
        ellipsis: true,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
      {
        title: '来源IP',
        key: 'ip',
        dataIndex: 'ip',
        ellipsis: true,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
    ];
    // 字段选择配置
    const rowSelection = {
      columnWidth: 30,
      onChange: (selectedRowKeys, selectedRows) => {
        const f = [...new Set([...selectedRowKeys, ...selectedRows.map((item) => item.req_id)])];
        const fx = [...this.state.selectedRows, ...selectedRows];
        const rows = f.map((id) => {
          return fx.find((it) => it.req_id === id);
        });
        this.setState({
          selectedRowKeys: f,
          selectedRows: rows,
        });
      },
      selectedRowKeys: selectedRowKeys,
    };
    return (
      <div className='detail-page'>
        {this.state.progress >= 0 && this.state.progress < 100 && this.state.running ? (
          <div className='lab-loading'>
            <Icon type='loading' />
            <p>试算进行中，当前已完成{this.state.progress}%</p>
          </div>
        ) : (
          ''
        )}
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: '20px' }}>
          {this.state.status !== 3 ? (
            <Button type='primary' style={{ marginRight: '20px' }} onClick={this.startTest}>
              开始试验
            </Button>
          ) : (
            <Button type='primary' style={{ marginRight: '20px' }} onClick={this.endTest}>
              停止试验
            </Button>
          )}
        </div>
        <Card style={{ padding: '15px 0' }}>
          <span>试验数据源: </span>
          <Radio.Group
            onChange={this.onSourceChange}
            value={this.state.source_type}
            disabled={
              this.state.status === 3 || (this.state.progress >= 0 && this.state.progress < 100 && this.state.running)
            }
          >
            <Radio value={1}>线上实时数据</Radio>
            <Radio value={2}>线上历史数据</Radio>
            <Radio value={3}>自定义数据</Radio>
          </Radio.Group>
          {this.state.source_type === 2 && (
            <div>
              <div className='source-content'>
                <span>ES历史数据</span>
                <RangePicker
                  showTime={{ format: 'HH:mm:ss' }}
                  format='YYYY-MM-DD HH:mm:ss'
                  placeholder={['开始时间', '结束时间']}
                  value={[moment(this.state.historyStart), moment(this.state.historyEnd)]}
                  allowClear={false}
                  disabled={this.state.progress >= 0 && this.state.progress < 100 && this.state.running}
                  disabledDate={(current) => {
                    // Can not select days before today and today
                    return current && current > moment().endOf('day');
                  }}
                  onChange={(e, dateString) => {
                    this.setState({
                      historyStart: e[0].format('YYYY-MM-DD HH:mm:ss'),
                      historyEnd:
                        moment(dateString[1]).valueOf() - moment().valueOf() > 0
                          ? moment().format('YYYY-MM-DD HH:mm:ss')
                          : dateString[1],
                    });
                  }}
                />
              </div>
              <p className='source-tip'>数据源可选择ES中历史数据进行试算，真实的线上数据对策略优化更有效。</p>
            </div>
          )}

          {this.state.source_type === 3 && (
            <div>
              <div className='source-content'>
                <Upload
                  accept='.xls,.xlsx'
                  name='file'
                  action={APIUrl + '/strategy-lab/source-upload'}
                  showUploadList={{ showRemoveIcon: true, showDownloadIcon: false }}
                  fileList={this.state.fileList}
                  onChange={this.onUploadChange}
                  data={{ lab_id: this.state.lab_id }}
                  headers={{
                    token: storage.token,
                    'X-User-Dept-Id': storage.dept,
                    modules: headerModules(this.props.menu.asideHighlight),
                  }}
                  disabled={this.state.progress >= 0 && this.state.progress < 100 && this.state.running}
                >
                  <Button disabled={this.state.progress >= 0 && this.state.progress < 100 && this.state.running}>
                    上传文件
                  </Button>
                </Upload>
                <p className='file-type'>
                  支持扩展名：xls、xlsx，点击下载
                  <Button
                    type='link'
                    onClick={this.downloadExample}
                    disabled={this.state.progress >= 0 && this.state.progress < 100 && this.state.running}
                  >
                    示例文件
                  </Button>
                </p>
              </div>
            </div>
          )}
        </Card>
        <Row type='flex' justify='space-between' align='middle' className='row-seach-box'>
          <p className='assess-result'>评估结果</p>
          <Col>
            {this.state.strategy_list && this.state.strategy_list.length > 0 && this.state.detailLoad && (
              <FilterTool
                key={this.state.source_start_time + this.state.source_end_time}
                reload={isKnownTime}
                data={filterItems}
                colNum={4}
                query={this.freshQueryList}
                refreshFilter={this.refreshFilter}
                isInitLoad={false}
                isOnChange={true}
                justify='end'
                style={{ flex: 1 }}
                disabled={
                  (this.state.progress >= 0 && this.state.progress < 100 && this.state.running) ||
                  (this.state.source_type === LABS_SOURCE_TYPE._ONLINE && this.state.status === LABS_STATUS._RUNNING)
                }
              />
            )}
          </Col>
        </Row>
        <Row className='dashbord-row'>
          <SpreadBar data={this.state.requests} hideDetail={true} />
        </Row>
        <Row className='dashbord-row'>
          <RequestTrend
            actionType={'strategyLabsApi'}
            isDownTitle={true}
            isStopTime={this.state.status === 3}
            data={this.state.strategy_trend || []}
            requestParam={this.requestParam}
          />
        </Row>
        <div className='risk-trend-boxs' style={{ margin: '20px 0' }}>
          <div className='chart-head' style={{ display: 'flex', justifyContent: 'space-between' }}>
            <h4>命中详情</h4>
            <Button type='primary' onClick={this.resultDownload.bind(this, false)} disabled={this.state.status === 3}>实验结果下载</Button>
            <Button type='primary' style={{ marginLeft: 20 }} onClick={this.resultDownAll} disabled={this.state.status === 3}>实验结果全部下载</Button>
          </div>

          {!isSelectedAll && selectedRowKeys && selectedRowKeys.length > 0 && (
            <Alert
              message={
                <>
                  已选择{selectedRowKeys.length}条数据
                  <Button type='link' style={{ marginLeft: '20px' }} onClick={this.clearSelected}>
                    清空
                  </Button>
                </>
              }
              type='success'
              style={{ marginTop: '10px' }}
            />
          )}

          <HitList
            {...this.state}
            {...this.props}
            columns={columns}
            showDetail={this.HitDetail}
            queryList={this.freshHitList}
            onChangePagination={this.onChangePagination}
            queryTableParams={this.queryTableParams}
            refreshTableFilter={this.refreshTableFilter}
            // expandedRowRender={this.expandedRowRender}
            rowKey={'req_id'}
            rowSelection={rowSelection}
            showSizeChanger={this.state.status === 3 ? false : true}
          />
        </div>
        <div className='risk-trend-box' style={{ margin: '20px 0' }}>
          <div className='chart-head'>
            <h4>异常详情</h4>
          </div>

          <ErrorList
            {...this.state.errorLists}
            {...this.props}
            columns={[
              {
                key: 'req_time',
                dataIndex: 'req_time',
                title: '时间',
                render: (text) => {
                  return moment(Number(text)).format('YYYY-MM-DD HH:mm:ss');
                },
              },
              {
                key: 'result',
                dataIndex: 'result',
                title: '异常信息',
                ellipsis: true,
                render: (text, record) => {
                  return (
                    <div style={{ cursor: 'pointer' }} onClick={this.openShowError.bind(this, text)}>
                      {text}
                    </div>
                  );
                },
              },
            ]}
            queryList={this.freshErrorQueryList}
            onChangePagination={this.onChangePaginationError}
            queryTableParams={this.queryTableParams}
            refreshTableFilter={this.refreshTableFilter}
            rowKey={'req_id'}
            showSizeChanger={this.state.status === 3 ? false : true}
          />
        </div>
      </div>
    );
  }
}

export default LabDetail;
